/**
 * @ClassName ComicFragment
 * @Author 24
 * @Date 2024/5/26 14:36
 * @Version 1.0.0
 * freedom is the oxygen of the soul.
 **/

package cn.edu.nchu.comic_strip.ui.bookpage;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import java.util.Locale;

import cn.edu.nchu.comic_strip.App;
import cn.edu.nchu.comic_strip.MainActivity;
import cn.edu.nchu.comic_strip.R;
import cn.edu.nchu.comic_strip.database.dao.PageDao;
import cn.edu.nchu.comic_strip.entity.Page;
import cn.edu.nchu.comic_strip.ui.bookmark.BookMarkBookDetailActivity;
import cn.edu.nchu.comic_strip.ui.collection.CollectionBookDetailActivity;


public class BookPageFragment extends Fragment implements TextToSpeech.OnInitListener {

    private ImageView imageView;
    private TextView titleView;
    private TextView summaryView;
    private TextView pageView;
    private ImageButton collectionButton;
    private ImageButton bookmarkButton;
    private Button textSizeButton;
    private ImageButton textReadButton;
    private SeekBar seekBar;
    private LinearLayout navigationLayout;
    private Button lastPageButton;
    private Button nextPageButton;
    private TextView seekBarValue;
    private ImageButton protectEyeButton;
    private Page comicData;
    private int page;
    private int sumPages;
    private TextToSpeech tts;
    private UtteranceProgressListener utteranceProgressListener;

    private PageDao pageDao = App.getAppDatabase().getPageDao();
    private int[] titleTextSize = {18, 22, 32};
    private int[] summaryTextSize = {14, 18, 24};
    private int[] pageTextSize = {12, 16, 22};
    private String[] textSizeButtonText = {"小", "中", "大"};
    private boolean isProtect;
    private int textSizeIndex = 0;
    private ComicFragmentButtonClickListener buttonClickListener;
    private float[] voice = {0.5f, 0.8f, 1.0f};
    private int voiceIndex = 1;

    private static final String PREFS_NAME = "MyPrefsFile";
    private static final String FRAGMENT_NAME = "ComicFragment";
    private static final String AUTO_PLAY = "AutoPlay";
    private long startTime;


    /**
     * 进入阅读页面时计算时间
     * @param savedInstanceState If the fragment is being re-created from
     * a previous saved state, this is the state.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取当前时间
        startTime = System.currentTimeMillis();
    }

    
    @Override
    public void onResume() {
        super.onResume();
        // 加载保存的时间
        SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
        int totalTime = settings.getInt(FRAGMENT_NAME, 0);
        if (settings.getBoolean(AUTO_PLAY, false)) {    // 如果是自动播放，进行自动朗读
            autoRead();
        }
        // 计算累计时间并保存
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        totalTime += elapsedTime / 1000; // 转换为秒
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(FRAGMENT_NAME, totalTime);
        editor.apply();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_book_page, container, false);
        imageView = view.findViewById(R.id.image_view);   // 获取图片组件
        titleView = view.findViewById(R.id.title_view);    // 获取标题组件
        summaryView = view.findViewById(R.id.summary_view);    // 获取内容组件
        pageView = view.findViewById(R.id.page_view);  // 获取页数组件
        collectionButton = view.findViewById(R.id.collection_button);    // 获取收藏按钮组件
        bookmarkButton = view.findViewById(R.id.bookmark_button);    // 获取书签按钮组件
        textSizeButton = view.findViewById(R.id.text_size_button);  // 获取字体按钮组件
        textReadButton = view.findViewById(R.id.text_read_button);  // 获取朗读按钮组件
        seekBar = view.findViewById(R.id.seekBar);// 获取进度条组件
        navigationLayout = view.findViewById(R.id.navigationLayout);//获取可隐藏式组件
        lastPageButton = view.findViewById(R.id.prevButton);//获取上一页按钮
        nextPageButton = view.findViewById(R.id.nextButton);//获取下一页按钮
        protectEyeButton = view.findViewById(R.id.protectEyeImageButton);//获取护眼模式按钮
        seekBarValue = view.findViewById(R.id.seekBarValue);//获取滑动条值
        tts = new TextToSpeech(requireContext(),this);
        tts.setPitch(voice[1]);
        utteranceProgressListener = new UtteranceProgressListener() {
            @Override
            public void onStart(String s) {
                System.out.println("开始朗读") ;
            }
            @Override
            public void onDone(String s) {
                if (buttonClickListener != null) {
                    buttonClickListener.onNextPageClicked();
                }
                System.out.println("朗读结束");
                textReadButton.setBackground(requireContext().getDrawable(R.drawable.not_read_button_background));
            }

            @Override
            public void onError(String s) {
            }
        };


        Bundle bundle = getArguments();   // 接收数据
        if (bundle != null) {
            comicData = (Page) bundle.getSerializable("comicData");
            sumPages = bundle.getInt("sumPages"); // 获取总页数
            textSizeIndex = bundle.getInt("textSizeIndex");
            isProtect = bundle.getBoolean("isProtect");
        }

        //获取当前页标
        setPage(comicData.getPageNum());   // 设置页数

        modifyStyle();  // 修改样式以及嵌入数据

        textSizeButton.setOnClickListener(v -> {    // 点击字体大小按钮事件
            if (buttonClickListener != null) {
                buttonClickListener.onTextSizeButtonClick();
            }
        });

        // 设置SeekBar的最大值
        seekBar.setMax(sumPages - 1);

        // 设置SeekBar的当前进度
        seekBar.setProgress(comicData.getPageNum() - 1);

        textReadButton.setOnClickListener(v -> read()); // 点击朗读按钮事件

        textReadButton.setOnLongClickListener(v ->  {   // 长按朗读按钮修改音色
            choiceVoice(v);
            return true;
        });

        protectEyeButton.setOnClickListener(v -> changeBackgroundColor()); // 点击护眼按钮事件

        collectionButton.setOnClickListener(v -> collectionClick()); // 点击收藏按钮事件
        bookmarkButton.setOnClickListener(v -> bookmarkClick());    // 点击书签按钮事件

        collectionButton.setOnLongClickListener(v -> {  // 长按收藏按钮跳转到收藏Fragment
            longCollectionClick();
            return true; // 事件已处理
        });
        bookmarkButton.setOnLongClickListener(v -> {    // 长按书签按钮跳转到书签Fragment
            longBookmarkClick();
            return true; // 事件已处理
        });

        lastPageButton.setOnClickListener(v -> lastPageClick()); // 点击上一页事件
        lastPageButton.setOnLongClickListener(v -> {    // 长按上一页按钮跳转到第一面
            longLastPageButtonClick();
            return true; // 事件已处理
        });

        nextPageButton.setOnClickListener(v -> nextPageClick()); // 点击下一页事件
        nextPageButton.setOnLongClickListener(v -> {    // 长按下一页按钮跳转到最后一面
            longNextPageButtonClick();
            return true; // 事件已处理
        });
        pageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (navigationLayout.getVisibility() == View.VISIBLE) {
                    navigationLayout.setVisibility(View.GONE);
                } else {
                    navigationLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        // 监听SeekBar进度变化
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekBarValue.setText(String.valueOf(progress + 1));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarValue.setVisibility(View.VISIBLE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 用户停止拖动SeekBar时，执行页面切换操作
                seekBarValue.setVisibility(View.GONE);
                buttonClickListener.onSelectPageClicked(seekBar.getProgress() + 1);
                seekBar.setProgress(comicData.getPageNum() - 1);
            }
        });

        return view;
    }

    private void changeBackgroundColor() {
        if (protectEyeButton.getTag().equals("关闭")){
            protectEyeButton.setTag("开启");
            protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_protect_eye));
            buttonClickListener.protectEye(true);
        }else {
            protectEyeButton.setTag("关闭");
            protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_no_protect_eye));
            buttonClickListener.protectEye(false);
        }
    }

    private void lastPageClick() {
        buttonClickListener.onSelectPageClicked(comicData.getPageNum()-1);
    }

    private void longLastPageButtonClick() {
        buttonClickListener.onSelectPageClicked(1);
    }

    private void nextPageClick() {
        buttonClickListener.onSelectPageClicked(comicData.getPageNum()+1);
    }

    private void longNextPageButtonClick() {
        buttonClickListener.onSelectPageClicked(sumPages);
    }

    @SuppressLint("SetTextI18n")    // 界面处理
    public void modifyStyle() {

        // 页处理
        if (comicData.getPageNum() == -1) {   // 是封面页
            ViewGroup.LayoutParams layoutParamsForImage = imageView.getLayoutParams();  // 获取当前 ImageView 的布局参数
            layoutParamsForImage.height = 1240;    // 设置高度值
            imageView.setLayoutParams(layoutParamsForImage);    // 应用新的布局参数
            titleView.setTextSize(42);  // 放大标题字体
            ViewGroup.MarginLayoutParams layoutParamsForSummary = (ViewGroup.MarginLayoutParams)
                    summaryView.getLayoutParams(); // 获取当前 TextView 的布局参数
            layoutParamsForSummary.topMargin = -50;   // 设置上边距值
            summaryView.setLayoutParams(layoutParamsForSummary);    // 应用新的布局参数
            summaryView.setTextSize(32);    // 放大作者字体

            // 确保 summaryView 自动换行
            summaryView.setSingleLine(false);
            summaryView.setEllipsize(null);
            summaryView.setMaxLines(10);  // 设置最大行数，根据需要调整

            // 设置 summaryView 的文本内容
            summaryView.setText(comicData.getSummary());
        } else if (comicData.getPageNum() == 0) { // 是简介页
            textSizeButton.setVisibility(View.VISIBLE); // 字体大小按钮可见
        } else {    // 是正文页
            pageView.setVisibility(View.VISIBLE);   // 页数可见
            pageView.setText("第 " + comicData.getPageNum() + " 页/共 " + sumPages + " 页");

            collectionButton.setVisibility(View.VISIBLE);   // 收藏按钮可见
            bookmarkButton.setVisibility(View.VISIBLE); // 书签按钮可见
            textSizeButton.setVisibility(View.VISIBLE); // 字体大小按钮可见
        }

        // 内容处理
        if (comicData.getSummary() != null && !comicData.getSummary().equals("")
                && comicData.getPageNum() >= 1) {  // 如果有内容并且不是标题页
            summaryView.setBackgroundResource(R.drawable.border_radius);    // 设置背景
        }

        // 按钮处理
        if (comicData.getIsCollection()== 1) { // 如果已经是收藏的了 修改按钮样式
            collectionButton.setImageResource(R.drawable.collection);
        }
        if (comicData.getIsBookmark() == 1) {   // 如果已经有书签了 修改按钮样式
            bookmarkButton.setImageResource(R.drawable.bookmrak);
        }

        // 解析资源名称字符串，获取对应的资源 ID
        int resourceId = requireContext().getResources().getIdentifier(comicData.getImageResId(), "drawable", requireContext().getPackageName());
        // 文本处理
        imageView.setImageResource(resourceId);  // 添加图片到组件
        titleView.setText(comicData.getTitle());   // 添加标题到组件
        summaryView.setText(comicData.getSummary());   // 添加内容到组件
        textSizeButton.setText(textSizeButtonText[textSizeIndex]); // 添加字体大小到组件

        if(protectEyeButton != null && isProtect){
            protectEyeButton.setTag("开启");
            protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_protect_eye));
        }
        else if(protectEyeButton != null){
            protectEyeButton.setTag("关闭");
            protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_no_protect_eye));
        }

        // 字体大小处理
        if (comicData.getPageNum() >= 1) {
            titleView.setTextSize(titleTextSize[textSizeIndex]);    // 改变标题大小
            summaryView.setTextSize(summaryTextSize[textSizeIndex]);    // 改变内容大小
            pageView.setTextSize(pageTextSize[textSizeIndex]);  // 改变页数大小
            textSizeButton.setText(textSizeButtonText[textSizeIndex]);  // 改变字体大小按钮的字体
        }
    }

    private void collectionClick() { // 收藏按钮
        if (comicData.getIsCollection() == 1) {   // 已经在收藏了
            // 数据库操作删除收藏
            pageDao.removeCollection(comicData.getId());
            comicData.setIsCollection(0);
            collectionButton.setImageResource(R.drawable.not_collection);  // 修改按钮样式
            Toast.makeText(getActivity(), "已取消收藏", Toast.LENGTH_SHORT).show();
        } else {    // 还没有收藏
            // 数据库操作添加收藏
            pageDao.addCollection(comicData.getId());
            comicData.setIsCollection(1);
            collectionButton.setImageResource(R.drawable.collection);    // 修改按钮样式
            Toast.makeText(getActivity(), "已成功收藏", Toast.LENGTH_SHORT).show();
        }
    }

    private void bookmarkClick() {   // 书签按钮
        if (comicData.getIsBookmark() == 1) {   // 已经有书签了
            // 数据库操作删除书签
            pageDao.removeBookmark(comicData.getId());
            comicData.setIsBookmark(0);
            bookmarkButton.setImageResource(R.drawable.not_bookmark);  // 修改按钮样式
            Toast.makeText(getActivity(), "取消书签", Toast.LENGTH_SHORT).show();
        } else {    // 还没有书签
            // 数据库操作添加书签
            pageDao.addBookmark(comicData.getId());
            comicData.setIsBookmark(1);
            bookmarkButton.setImageResource(R.drawable.bookmrak);  // 修改按钮样式
            Toast.makeText(getActivity(), "添加书签", Toast.LENGTH_SHORT).show();
        }
    }

    private void longCollectionClick() {    // 长按收藏按钮
        Intent intent = new Intent(getActivity(), CollectionBookDetailActivity.class);  // 创建跳转到目标 Activity 的 Intent
        intent.putExtra("bookId", comicData.getBookId());   // 去收藏Fragment
        startActivity(intent);  // 启动目标 Activity
    }

    private void longBookmarkClick() {  // 长按书签按钮
        Intent intent = new Intent(getActivity(), BookMarkBookDetailActivity.class);  // 创建跳转到目标 Activity 的 Intent
        intent.putExtra("bookId", comicData.getBookId());   // 去收藏Fragment
        startActivity(intent);  // 启动目标 Activity
    }



    private void read() {   // 朗读
        // 点击按钮，改变自动朗读的值
        SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(AUTO_PLAY, !settings.getBoolean(AUTO_PLAY, false));
        editor.apply();
        
        autoRead();
    }
    private void autoRead() {   // 自动朗读
        if (textReadButton.getTag().equals("未读")){
            textReadButton.setTag("在读");
            textReadButton.setBackground(this.getResources().getDrawable(R.drawable.read_button_background));
            tts.speak(comicData.getTitle()+"...   "+comicData.getSummary(),TextToSpeech.QUEUE_FLUSH, null,"1");
        }else {
            textReadButton.setTag("未读");
            textReadButton.setBackground(this.getResources().getDrawable(R.drawable.not_read_button_background));
            tts.stop();
        }
    }

    private void choiceVoice(View view) {    // 修改语音
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext())
                .setTitle("设置朗读性别")
                .setIcon(R.mipmap.ic_launcher)
                .setSingleChoiceItems(new String[]{"男声", "中性", "女声"}, voiceIndex, (dialog13, which) -> {
                    voiceIndex = which;//得到被点击的序号which
                })
                .setPositiveButton("确定", (dialog12, which) -> {
                    tts.setPitch(voice[voiceIndex]);    // 设置音色
                    dialog12.dismiss();
                })
                .setNegativeButton("取消", (dialog1, which) -> dialog1.dismiss());
        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {   // 自动轮播
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && getActivity() != null) {
            if (getActivity() instanceof BookPageActivity) {
                BookPageActivity comicActivity = (BookPageActivity) getActivity();
                comicActivity.stopAutoScroll();
            }
        }
    }

    @Override
    public void onInit(int status) {  //初始化语音
        if (status == TextToSpeech.SUCCESS) {
            tts.setOnUtteranceProgressListener(utteranceProgressListener);
            int result1 = tts.setLanguage(Locale.CHINA);
            if (result1 == TextToSpeech.LANG_MISSING_DATA
                    || result1==TextToSpeech.LANG_NOT_SUPPORTED)
            {
                Toast.makeText(requireContext(), "数据丢失或不支持:"+result1+";", Toast.LENGTH_SHORT).show();
            }
        }
    }
    public void onDestroy() {
        // 生命周期中结束
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        textReadButton.setBackground(this.getResources().getDrawable(R.drawable.not_read_button_background));
        super.onDestroy();
    }
    public void onStop() {
        super.onStop();
        tts.stop(); // 不管是否正在朗读TTS都被打断
        tts.shutdown(); // 关闭，释放资源
        textReadButton.setBackground(this.getResources().getDrawable(R.drawable.not_read_button_background));
    }

    public interface ComicFragmentButtonClickListener {
        void onTextSizeButtonClick();
        void onNextPageClicked();
        void onSelectPageClicked(int pagesIndex);
        void protectEye(boolean isStart);
    }


    public BookPageFragment() {
    }

    public ImageView getImageView() {
        return imageView;
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

    public TextView getTitleView() {
        return titleView;
    }

    public void setTitleView(TextView titleView) {
        this.titleView = titleView;
    }

    public TextView getSummaryView() {
        return summaryView;
    }

    public void setSummaryView(TextView summaryView) {
        this.summaryView = summaryView;
    }

    public TextView getPageView() {
        return pageView;
    }

    public void setPageView(TextView pageView) {
        this.pageView = pageView;
    }



    public Button getTextSizeButton() {
        return textSizeButton;
    }

    public void setTextSizeButton(Button textSizeButton) {
        this.textSizeButton = textSizeButton;
    }


    public Page getComicData() {
        return comicData;
    }

    public void setComicData(Page comicData) {
        this.comicData = comicData;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getSumPages() {
        return sumPages;
    }

    public void setSumPages(int sumPages) {
        this.sumPages = sumPages;
    }

    public TextToSpeech getTts() {
        return tts;
    }

    public void setTts(TextToSpeech tts) {
        this.tts = tts;
    }

    public UtteranceProgressListener getUtteranceProgressListener() {
        return utteranceProgressListener;
    }

    public void setUtteranceProgressListener(UtteranceProgressListener utteranceProgressListener) {
        this.utteranceProgressListener = utteranceProgressListener;
    }

    public int[] getTitleTextSize() {
        return titleTextSize;
    }

    public void setTitleTextSize(int[] titleTextSize) {
        this.titleTextSize = titleTextSize;
    }

    public int[] getSummaryTextSize() {
        return summaryTextSize;
    }

    public void setSummaryTextSize(int[] summaryTextSize) {
        this.summaryTextSize = summaryTextSize;
    }

    public int[] getPageTextSize() {
        return pageTextSize;
    }

    public void setPageTextSize(int[] pageTextSize) {
        this.pageTextSize = pageTextSize;
    }

    public String[] getTextSizeButtonText() {
        return textSizeButtonText;
    }

    public void setTextSizeButtonText(String[] textSizeButtonText) {
        this.textSizeButtonText = textSizeButtonText;
    }

    public int getTextSizeIndex() {
        return textSizeIndex;
    }

    public void setTextSizeIndex(int textSizeIndex) {
        this.textSizeIndex = textSizeIndex;
    }

    public ComicFragmentButtonClickListener getButtonClickListener() {
        return buttonClickListener;
    }

    public void setButtonClickListener(ComicFragmentButtonClickListener buttonClickListener) {
        this.buttonClickListener = buttonClickListener;
    }

    public float[] getVoice() {
        return voice;
    }

    public void setVoice(float[] voice) {
        this.voice = voice;
    }

    public int getVoiceIndex() {
        return voiceIndex;
    }

    public void setVoiceIndex(int voiceIndex) {
        this.voiceIndex = voiceIndex;
    }

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public SeekBar getSeekBar() {
        return seekBar;
    }

    public void setSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;
    }

    public ImageButton getProtectEyeButton() {
        return protectEyeButton;
    }

    public void setProtectEyeButton(ImageButton protectEyeButton) {
        this.protectEyeButton = protectEyeButton;
    }
}